using OpenCvSharp;
using VideoRecorder.Util;

namespace VideoRecorder.Media;

/// <summary>
/// OpenCV摄像头
/// </summary>
public class CvCamera {
    private readonly TimedIntervalTask _task;
    private VideoCapture _capture;

    /// <summary>摄像头索引</summary>
    public int Index { get; set; }
    public int Width { get; set; } = 800;
    public int Height { get; set; } = 600;
    public int Fps { get; set; } = 30;

    private volatile bool _running;
    public bool IsRunning => _running;

    public event Action<Mat> ReceivedFrame;

    private readonly object _locker = new();

    public CvCamera() {
        _task = new TimedIntervalTask(CaptureTask, 30);
    }

    private void CaptureTask() {
        if (_capture != null) {
            var mat = _capture.RetrieveMat();
            if (!mat.Empty()) {
                lock (_locker) {
                    if (_running) {
                        ReceivedFrame?.Invoke(mat);
                    }
                }
            }
        }
    }

    public void Start() {
        if (IsRunning) return;
        _running = true;
        _capture = new VideoCapture(Index);
        _capture.FrameWidth = Width;
        _capture.FrameHeight = Height;
        _capture.Fps = Fps;

        _task.IntervalTime = GetFpsIntervalTime();
        _task.Startup();
    }

    public void Stop() {
        if (!IsRunning) return;
        _running = false;
        _task.Stop();
        _capture.Release();
        _capture.Dispose();
        _capture = null;
    }

    private int GetFpsIntervalTime() {
        var fps = Fps;
        var interval = WebCamHelper.GetFpsIntervalTime(ref fps);
        Fps = fps;
        return interval;
    }
}
